/**
 * Copyright (C) 2010 Cloudfarming <info@cloudfarming.nl>
 *
 * Licensed under the Eclipse Public License - v 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.eclipse.org/legal/epl-v10.html
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package nl.cloudfarming.client.area.field.shape;

import nl.cloudfarming.client.area.field.pref.AreaFieldPreference;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.swing.filechooser.FileFilter;
import nl.cloudfarming.client.area.field.AreaFieldModule;
import nl.cloudfarming.client.util.FileCopier;
import org.netbeans.api.progress.ProgressHandle;
import org.netbeans.api.progress.ProgressHandleFactory;
import org.openide.filesystems.FileChooserBuilder;
import org.openide.util.Cancellable;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle;
import org.openide.util.NbPreferences;

public final class ShapeFilePicker {

    public static String FILECHOOSER_DIR = NbBundle.getMessage(AreaFieldModule.class, "shape.filepicker.chooser.directory");
    public static String FILECHOOSER_TITLE = NbBundle.getMessage(AreaFieldModule.class, "shape.filepicker.title");
    public static String FILECHOOSER_APPROVE_TEXT = NbBundle.getMessage(AreaFieldModule.class, "shape.filepicker.chooser.button.approve.text");
    
    private static final String USER_HOME = "user.dir";
    private boolean cancelled = false;
    //
    // the progress handle, creates a progress bar in the lower right corner of the screen
    private final ProgressHandle progressHandle = ProgressHandleFactory.createHandle("processing shape files", new Cancellable() {

        @Override
        public boolean cancel() {
            cancelled = true;
            progressHandle.finish();
            return cancelled;
        }
    });

    /**
     * Show the filepicker
     */
    public void show() {
        // Show the actual picker and use the returned File-object
        File selectedFileOrDir = showPicker();

        // Should not be null
        if (selectedFileOrDir == null) {
            return;
        }

        try {
            File destinationDir = getDestination();

            // Process selectedFileOrDir as either a directory or as a file
            if (selectedFileOrDir.isDirectory()) {
                FileCopier.copyDirectory(selectedFileOrDir, destinationDir, ".shp", true);

                
                

                if (destinationDir.listFiles().length < 1) {
                    throw new FileNotFoundException("No files found in " + destinationDir.getAbsolutePath());
                } else {
                    // Process all files in directory
                    progressHandle.start(destinationDir.listFiles().length);
                    for (File file : destinationDir.listFiles()) {
                        if (file.getName().toLowerCase().endsWith(".shp")) {
                            ShapeFileProcessor processor = new ShapeFileProcessor(file);
                            processor.process();
                            progressHandle.progress(file.getName() + " processed", 1);
                        } else {
                            progressHandle.progress(1);
                        }
                    }
                }
            } else { // If we get here the user selected an .shp file rather then a directory

                // Check if selected file is .shp type
                if (selectedFileOrDir.getName().toLowerCase().endsWith(".shp")) {
                    progressHandle.start(1);
                    // Copy selected file + bundled files to the destination directory
                    FileCopier.copyFile(selectedFileOrDir, destinationDir, true);

                    // Process the shapefiles
                    File shapeFileToProcess = new File(destinationDir.getPath() + File.separator + selectedFileOrDir.getName());
                    ShapeFileProcessor processor = new ShapeFileProcessor(shapeFileToProcess);
                    processor.process();

                    progressHandle.progress(destinationDir.getName() + " processed", 1);
                }
            }
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        } finally {
            progressHandle.finish();
        }
    }

    /**
     * Shows the actual filepicker and return the selected file or dir
     * @return The selected file
     */
    private File showPicker() {
        String name = AreaFieldPreference.LAST_SHAPE_DIR.getValue();
        File userHome = (name.equals("")) ? new File(System.getProperty(USER_HOME)) : new File(name);

        FileFilter ff = new FileFilter() {

            @Override
            public boolean accept(File f) {
                String name = f.getName().toLowerCase();
                return f.isDirectory() || (f.isFile() && name.endsWith(".shp"));
            }

            @Override
            public String getDescription() {
                return "Shape file (*.shp)";
            }
        };

        FileChooserBuilder fcb = new FileChooserBuilder(FILECHOOSER_DIR);
        fcb.setTitle(FILECHOOSER_TITLE);
        fcb.setDefaultWorkingDirectory(userHome);
        fcb.addFileFilter(ff);
        fcb.setApproveText(FILECHOOSER_APPROVE_TEXT);
        File file = fcb.showOpenDialog();

        // file will be null if cancel is pressed
        if (file != null) {
            // save the file path for next time window is opened
            AreaFieldPreference.LAST_SHAPE_DIR.saveValue(file.getPath());
        }

        return file;
    }

    /**
     * Get the destination dir for copy action
     * @return Destination for shape-files or shapefile dir to copy to
     */
    private File getDestination() {
        StringBuilder sb = new StringBuilder(NbPreferences.root().get("user.dir", System.getProperty("user.dir")));
        sb.append("/");
        sb.append(AreaFieldPreference.SHAPE_FILE_ARCHIVE_DIR.getValue());
        String appDir = sb.toString();
        return new File(appDir);
    }
}
